// @ 516
// _(:з」∠)_

define([], function() {
    'use strict';

    const RST = {};

    // request basic data
    RST['basic'] = function( filePath, param, execute ) {
        Loading.basic();

        fetch( filePath, {
            method: "GET"
        }).then( function( response ) {
            if ( response.ok ) {
                return response.json();
            } else {
                return Promise.reject( response );
            }
        }).then( function( result ) {
            Loading.remove();

            if ( result  && result.status == 1) {
                ( execute && typeof( execute ) === "function" ) && execute( result );
            } else if ( result ) {
                ( execute && typeof( execute ) === "function" ) && execute( result );
            } else {
                Popup.tipPopup({
                    type: "toast",
                    content: `当前无数据！`
                });
            }
        }).catch( function( err ) {
            Loading.remove();
            
            let content = "";
            switch( err.status ) {
                case 400:
                    content = "请求语法错误";
                    break;
                case 403:
                    content = "服务器拒绝请求";
                    break;
                case 404:
                    content = "服务器未找到文件";
                    break;
                case 408:
                    content = "服务器请求等待超时";
                    break;
                case 500:
                    content = "服务器错误，请求失败";
                    break;
                case 503:
                    content = "服务器当前无法使用";
                    break;
            }

            if ( content != "" ) {
                Popup.tipPopup({
                    type: "toast",
                    content: `<p>状态: ${ err.status }</p>
                                <p>状态值: ${ err.statusText }</p>
                                <p>状态释义: ${ content }</p>
                                <!-- <p>错误路径: ${ err.url }</p> -->`
                });
            } else {
                if ( err.status == null ) console.log( err.stack );
                
                Popup.tipPopup({
                    type: "toast",
                    content: `当前无数据！`
                });
            }
        });   
    }

    RST["XML"] = function( filePath, param, execute ) {
        let url = encodeURI( NetWorkPath + filePath );
        fetch( url, {
            method: "GET"
        }).then( function( result ) {
            if ( result.ok ) { return result.text(); }
        }).then( function( data ) {
            if ( data ) {
                let table = data.split("<ss:Table>")[1].split("</ss:Table>")[0],
                    rowList = table.split("<ss:Row>");

                let jsonKey = [], xmlJson = [], station = {},
                    rowFirst = rowList[1].split('Data ss:Type="');

                for ( let x = 1; x < rowFirst.length; x++ ) {
                    jsonKey.push( rowFirst[x].split("</Data>")[0].split('">')[1] );
                }

                for ( let x = 2; x < rowList.length; x++ ) {
                    let xmlItem = {},
                        rowItem = rowList[x].split('Data ss:Type="');

                    for ( let y = 1; y < rowItem.length; y++ ) {
                        xmlItem[ jsonKey[y-1] ] = rowItem[y].split("</Data>")[0].split('">')[1];
                    }

                    xmlJson.push( xmlItem );
                }

                for ( let x = 0; x < xmlJson.length; x+=12 ) {
                    station[ xmlJson[x].sta_id ] = [];
                    for ( let y = x; y < ( x + 12 ); y++ ) {
                        station[ xmlJson[x].sta_id ].push( xmlJson[y] );
                    }
                }

                ( execute && typeof( execute ) === "function" ) && execute( station );
            }
        }).catch( function( err ) { console.log( "request xml data error" ); });
    }

    RST['weatherStation'] = function( path, execute ) {
        let http = "http://openapi.ecois.info";

        fetch( http + path, {
            method: "GET",
            headers: { "X-Access-Token": "Q1cmP$rCyYES73-LtaM-EZXMS4$P5OZx" }
        }).then( function( response ) {
            if ( response.ok ) { return response.json(); }
        }).then( function( result ) {
            if ( result.data  && result.error == 10000 ) {
                ( execute && typeof( execute ) === "function" ) && execute( result.data );
            } else { console.log( result.data ); }
        }).catch( function( err ) { console.log( "request weather station info error" ); });
    }
    
    // request lngLat turn address
    RST['lngLatTurnAddress'] = function( latlng, execute ) {
        let url = "https://regeo.market.alicloudapi.com/v3/geocode/regeo?";
        fetch( url + "extensions=base&location="+latlng.lng+","+latlng.lat+"&output=json", {
            method: "GET",
            headers:{ "Authorization": "APPCODE ed5dea8889064fedaea4319a93c490e5" }
        }).then( function( result ) {
            if ( result.ok ) { return result.json(); }
        }).then( function( data ) {
            if ( data  && data.status == 1 ) {
                ( execute && typeof( execute ) === "function" ) && execute( data );
            }
        }).catch( function( err ) { console.log( "request address data error" ); });   
    }

    // request area bounds - source tianditu api
    RST['areaBounds'] = function( filePath, param, type, execute ) {
        let url = "";
        if ( type == "tianditu" ) {
            url = "http://map.tianditu.gov.cn/data/query?postStr=%7B%22yingjiType%22%3A0%2C%22sourceType%22%3A0%2C%22keyWord%22%3A%22"+ encodeURI( param ) +"%22%2C%22level%22%3A10%2C%22mapBound%22%3A%22116.40152%2C36.16338%2C118.12775%2C37.14061%22%2C%22queryType%22%3A1%2C%22start%22%3A0%2C%22count%22%3A10%2C%22queryTerminal%22%3A10000%7D&type=query";
        } else if ( filePath != "" && filePath.indexOf("http") < 0 ) {
            url = Path + filePath;
        }
    
        fetch( url, {
            method: "GET"
        }).then( function( result ) {
            if ( result.ok ) { return result.json(); }
        }).then( function( data ) {
            if ( data && type == "" ) {
                ( execute && typeof( execute ) === "function" ) && execute( data );
            } else if ( data && type == "tianditu" ) {
                let dataCv =  { "type":"GeometryCollection", "geometries": [] };
            
                for ( let x = 0; x < data.area.points.length; x++ ) {
                    let points = [],
                        region = data.area.points[x].region.split(","),
                        LineString = { "type":"LineString", "coordinates": [] };

                    for ( let y = 0; y < region.length; y++ ) {
                        let point = region[y].split(" ");
                        LineString.coordinates.push( point );
                    }

                    dataCv.geometries.push( LineString );
                }

                ( execute && typeof( execute ) === "function" ) && execute( dataCv );
            }
        }).catch( function( err ) { console.log( "request bounds data error" ); });   
    }

    // request area chromatic data
    RST['chromatic'] = function( filePath, param, execute ) {
        Loading.basic();

        let url = encodeURI( NetWorkPath + filePath );
        fetch( url, {
            method: "GET"
        }).then( function( result ) {
            if ( result.ok ) {
                return result.json();
            } else {
                return Promise.reject( result );
            }
        }).then( function( data ) {
            Loading.remove();

            if ( data && data.status === 1 ) {
                ( execute && typeof( execute ) === "function" ) && execute( data );
            } else {
                Popup.tipPopup({
                    type: "toast",
                    content: `当前无数据！`
                });
            }
        }).catch( function( err ) {
            Loading.remove();

            let content = ``;
            switch( err.status ) {
                case 404:
                    content += `<p>状态: ${ err.status }</p>
                                        <p>状态值: ${ err.statusText }</p>
                                        <p>状态释义: 未查询到符合当前条件的文件</p>
                                        <!-- <p>错误路径: ${ err.url }</p> -->`;
                break;
            }
            if ( content == "" ) {
                Popup.tipPopup({ type: "toast", content: `${ err.message }` });
            } else {
                Popup.tipPopup({ type: "toast", content: content });
            }
        });   
    }

    RST['Image'] = function( filePath, param, execute ) {
        Loading.basic();

        let url = encodeURI( NetWorkPath + filePath );
        fetch( url, {
            method: "GET"
        }).then( function( result ) {
            if ( result.ok ) {
                return result.json();
            } else {
                return Promise.reject( response );
            }
        }).then( function( data ) {
            Loading.remove();

            if ( data && data.status === 1 ) {
                ( execute && typeof( execute ) === "function" ) && execute( data );
            } else {
                Popup.tipPopup({
                    type: "toast",
                    content: `当前无数据！`
                });
            }
        }).catch( function( err ) {
            Loading.remove();

            Popup.tipPopup({
                type: "toast",
                content: `当前无数据！`
            });
        });   
    }

    RST['ContourImage'] = function( filePath, param, execute ) {
        fetch( filePath, {
            method: "GET"
        }).then( function( result ) {
            if ( result.ok ) {
                return result.json();
            } else {
                return Promise.reject( response );
            }
        }).then( function( data ) {
            ( execute && typeof( execute ) === "function" ) && execute( data );
        }).catch( function( err ) {
            Popup.tipPopup({ type: "toast", content: `当前等值线无数据！` });
        });   
    }

    window.RST = RST;

    return RST;
});